package com.example.rwq_test.niuke.list;

import java.util.List;

/**
 * 删除链表中的重复元素
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/10/20
 */
public class DeleteRepeat {

    //channel channelOption channelInitializer channelHandler channelPipeline channelFuture eventLoop EvenloopGroup bootStrap serviceBootstrap byteBuf codec
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(1);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(3);
        ListNode listNode5 = new ListNode(3);
        ListNode listNode6 = new ListNode(5);
        ListNode listNode7 = new ListNode(5);

        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        listNode6.next = listNode7;

        ListNode listNode = delAndRetainOne(listNode1);

        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    /**
     * 删除重复的保留一个
     *
     * @param head
     * @return
     */
    public static ListNode deleteAndRetainOne(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode cur = head;
        ListNode next = head.next;
        while (next != null) {
            if (cur.val == next.val) {
                cur.next = next.next;
                next = cur.next;
            } else {
                cur = cur.next;
                next = cur.next;
            }
        }
        return head;
    }

    public static ListNode delAndRetainOne(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        while (head.next != null && head.val == head.next.val) {
            head.next = head.next.next;
        }
        head.next = delAndRetainOne(head.next);
        return head;
    }

    /**
     * 删除所有重复的
     *
     * @param head
     * @return
     */
    public static ListNode deleteAllRepeat(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val == head.next.val) {
            while (head.next != null && head.val == head.next.val) {
                head = head.next;
            }
            return deleteAllRepeat(head.next);
        } else {
            head.next = deleteAllRepeat(head.next);
        }
        return head;
    }
}
